<?php
/**
 * Created by PhpStorm.
 * User: JieHuiLong
 * Date: 2016/11/7
 * Time: 14:05
 */

function getBrowerType()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $res = false;
    if (strpos($user_agent, 'MicroMessenger') === false) {
        $res = true;
    }
    return $res;
}


/*获取客户端ip*/
function getIp()
{
    if (isset($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], "unknown"))
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], "unknown"))
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if (isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else if (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else $ip = "";
    return ($ip);
}

//获取两个日期差
function getDiffTime($startTime, $endTime)
{
    $startTimeStr = strtotime($startTime);
    $endTimeStr = strtotime($endTime);
    $remain = $endTimeStr - $startTimeStr;
    $day = floor(($remain / 86400));
    $hour = floor(($remain - $day * 86400) / 3600);
    $minute = floor(($remain - $day * 86400 - $hour * 3600) / 60);
    return $day . '天' . $hour . '小时' . $minute . '分钟';
}


function http_post_data($url, $data_string)
{

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    curl_exec($ch);
    $return_content = ob_get_contents();
    ob_end_clean();

    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return array($return_code, $return_content);
}


/**
 * $filename  real file path
 * $delete_time cache save time xxx/minute
 * check cache update time
 */
function cache_check($filename, $delete_time = 0)
{
    if (is_file($filename)) {
        if ($delete_time) {
            $t = time();
            $ft = filemtime($filename);
            if ($t - $ft < $delete_time * 3600) {
                return true;
            }
        } else {
            return true;
        }
    }
    return false;
}

function getKeywordRand($num = 1, $arr = false)
{
    $res = array("天猫女装", "女装精品", "打折", "品牌折扣", "限时抢购", "特卖", "超值购", "超值", "专享价", "促销优惠", "促销活动", "品牌折扣", "打折信息", "化妆品", "海淘网", "海淘", "护肤品", "免税店", "美妆", "海外购", "正品化妆品", "淘宝", "团购", "商品团购", "本地生活", "团购大全", "餐饮团购", "化妆品团购", "数码团购", "网上购物", "网上商城", "网上买书", "购物中心", "在线购物", "图书", "影视", "音像", "教育音像", "CD", "DVD", "百货", "母婴", "家居", "家纺", "厨具", "化妆品", "美妆", "个人护理用品", "数码", "电脑", "笔记本", "u盘", "手机", "mp3", "mp4", "数码相机", "摄影", "摄像", "家电", "软件", "游戏", "服装", "鞋", "礼品箱包", "钟表首饰", "玩具", "运动健康用品", "九块邮", "折800", "九块九包邮", "9块9包邮", "9.9包邮", "九块邮官网", "爱淘宝", "导购", "淘宝导购", "淘宝达人推荐", "购物分享", "优惠券", "天猫优惠券", "天猫内部优惠券", "淘宝优惠券", "淘宝内部优惠券", "化妆品团购", "今日团购", "化妆品防伪", "化妆品验真", "真品联盟");
    $res = getShuffleRand($res, $num);
    if ($arr) return $res;
    return implode(',', $res);
}

/**
 * @param int $begin
 * @param int $end
 * @param int $limit
 * @return array
 */
function getNumberRand($begin = 0, $end = 20, $limit = 5)
{
    $rand_array = range($begin, $end);
    shuffle($rand_array); //调用现成的数组随机排列函数
    return array_slice($rand_array, 0, $limit); //截取前$limit个
}

function getShuffleRand($rand_array, $limit = 5)
{
    shuffle($rand_array); //调用现成的数组随机排列函数
    return array_slice($rand_array, 0, $limit); //截取前$limit个
}

/**
 * [isMobile 判断手机还是PC访问--Start]
 * @return boolean [false/true]
 * @Mender: JieHuiLong <jiehuilong@icloud.com>
 * @UpdateTime: 2016-01-14 14:24:21
 * @UpdateDescription: Description
 */
function isMobile()
{
    $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $useragent_commentsblock = preg_match('|\(.*?\)|', $useragent, $matches) > 0 ? $matches[0] : '';
    $mobile_os_list = array('Google Wireless Transcoder', 'Windows CE', 'WindowsCE', 'Symbian', 'Android', 'armv6l', 'armv5', 'Mobile', 'CentOS', 'mowser', 'AvantGo', 'Opera Mobi', 'J2ME/MIDP', 'Smartphone', 'Go.Web', 'Palm', 'iPAQ');
    $mobile_token_list = array('Profile/MIDP', 'Configuration/CLDC-', '160×160', '176×220', '240×240', '240×320', '320×240', 'UP.Browser', 'UP.Link', 'SymbianOS', 'PalmOS', 'PocketPC', 'SonyEricsson', 'Nokia', 'BlackBerry', 'Vodafone', 'BenQ', 'Novarra-Vision', 'Iris', 'NetFront', 'HTC_', 'Xda_', 'SAMSUNG-SGH', 'Wapaka', 'DoCoMo', 'iPhone', 'iPod');
    $found_mobile = checkSubstrs($mobile_os_list, $useragent_commentsblock) || checkSubstrs($mobile_token_list, $useragent);
    if ($found_mobile) {
        return true;
    } else {
        return false;
    }
}

function checkSubstrs($substrs, $text)
{
    foreach ($substrs as $substr) {
        if (false !== strpos($text, $substr)) {
            return true;
        }
    }

    return false;
}

//判断手机还是PC访问--End

/**
 * @param $str need to repalce strings
 * @return bool|mixed  error:return false normal: return res after replace,that type is string
 */
function delete_url($str)
{
    try {
        $str = preg_replace('/(https|http|ftp|rtsp|mms)?:\/\/[0-9a-z\.\/\-]+\/[0-9a-z\.\/\-]+\.([0-9a-z\.\/\-]+)/', '', $str);
        return $str;
    } catch (Exception $e) {
        return false;
    }
}

/**
 * @param $str need to format for string
 * @return bool|mixed  false: return false , true:return $str,that type is string
 */
function check_messy_code($str)
{
    $strOjb = preg_replace('/[^\x{4e00}-\x{9fff}]+/u', '', $str);
    if (mb_strlen($strOjb) < 7) {
        return false;
    }
    return $strOjb;
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = null, $format = 'Y-m-d H:i:s')
{
    $time = $time === null ? time() : intval($time);
    return date($format, $time);
}

/**
 * @param $url  website string
 * @return string Domain name
 */
function get_domain($url)
{
    preg_match('/\/\/(.*?)\//', $url, $matches);
    $strArr = explode('.', $matches[1]);
    $domian = array_slice($strArr, -2, 1)[0] . '.' . end($strArr);
    return strtolower($domian);
}

/**
 * Curl collect
 */
function curl($url)
{

    $SSL = substr($url, 0, 5) == "https" ? true : false;
    if ($SSL) {

        try {
            $data['html'] = file_get_contents($url);
            $data['http'] = 200;
        } catch (Exception $e) {
            $data['html'] = "";
        }
        $data['http'] = 200;
    } else {
        $data = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36');
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        $data['html'] = curl_exec($ch);
        $data['http'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $data['realUrl'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        curl_close($ch);
    }

    //get remote page encode
    $wcharset = preg_match("/<meta(.*?)charset=[^\w]?([-\w]+)/i", $data['html'], $charsetArr);
    $data['charset'] = strtolower(end($charsetArr));

    //convert origin encode
    if (!empty($data['charset'])) {
        try {
            $data['html'] = mb_convert_encoding($data['html'], 'UTF-8', $data['charset']);
            //get Title
            preg_match_all("/<title>(.*)<\/title>/s", $data['html'], $titleArr, PREG_PATTERN_ORDER);
            if (!empty(end($titleArr))) {
                $data['title'] = end($titleArr)[0];
            }
        } catch (Exception $e) {

        }
    }

    $data['encode'] = strtolower(mb_detect_encoding($data['html']));
    $data['ssl'] = $SSL;
    return $data;
}

//转码
function file_utf8($filepath)
{

    $f_contents = file_get_contents($filepath);
    $encoding = mb_detect_encoding($f_contents, array('GB2312', 'GBK', 'UTF-16', 'UCS-2', 'UTF-8', 'BIG5', 'ASCII'));
    $content_u = "";
    $hz = substr($filepath, strrpos($filepath, '.') + 1);
    if (strstr($hz, "csv")) {
        $filepath = fopen($filepath, 'r');
        while ($data = fgetcsv($filepath)) {
            //每次读取CSV里面的一行内容
            if ($encoding != false) {
                $buffer = iconv($encoding, 'UTF-8', $data[0]);
            } else {
                $buffer = mb_convert_encoding($data[0], 'UTF-8', 'Unicode');
            }
            $content_u .= $buffer . '!@#!@#';
        }
        fclose($filepath);
    } elseif (strstr($hz, "txt")) {
        $handle = fopen($filepath, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle);
                if ($encoding != false) {
                    $buffer = iconv($encoding, 'UTF-8', $buffer);
                } else {
                    $buffer = mb_convert_encoding($buffer, 'UTF-8', 'Unicode');
                }
                $content_u .= $buffer . '!@#!@#';
            }
        }
        fclose($handle);
    }
    return $content_u;
}
